<?php

namespace plugin\webman\common;
use support\Db;
use GatewayWorker\Lib\Gateway;
use support\Redis;

// 全局公共方法

class Common
{
    // 获取用户信息
    static function getUserInfo($uid){
 
        $ifexit = Db::table("wa_users")->where("id",$uid)->first();
        $url =  self::getsiteurl('siteurl');
       
        $user['id']=$uid;
        $user['username']=$ifexit->username;
        $user['nickname']=$ifexit->nickname;
        $user['coin']=$ifexit->score;
        $user['isrobot']=$ifexit->isrobot;
        $user['status']=$ifexit->status;
        $user['avatar']= $url."/app/admin/upload/img/avatar/".rand(1,30).'.jpg';
        return $user;
    }
    // 获取用户信息
    static function getUserInfo2($uid){
        $ifexit = Db::table("wa_users")->where("id",$uid)->first();
        $url =  self::getsiteurl('siteurl');
  
        $user['id']=(int)$uid;
        $user['username']=$ifexit->username;
        $user['nickname']=$ifexit->nickname;
        $user['coin']=$ifexit->score;
        $user['isrobot']=$ifexit->isrobot;
        $user['status']=$ifexit->status;
        $user['avatar']= $url ."/app/admin/upload/img/avatar/".rand(1,30).'jpg';
        return $user;
    }

    static function getsiteurl(){
        $option = Db::table("wa_options")->where("id",1)->first();
        $res = json_decode($option->value,true);
       
        return $res['logo']['siteurl'];
    }
    static  function object_array($array){
        if(is_object($array)){
          $array = (array)$array;
        }
        if(is_array($array)){
          foreach($array as $key=>$value){
            $array[$key] = self::object_array($value);
          }
        }
        return $array;
      }
    // 获取当前时间的期号
    static function getnowexpect(){
        $hour = date("H");
        $min =date("i");
        // $hour = 1;
        // $min =15;
        $a = $hour*60+$min;

        if($a<1000 && $a>100){
            $a='0'.$a;
        }
        if($a<100){
            $a='00'.$a;
        }
        return date('Ymd').$a;
    }

    // 获取用户信息
    static function getUserInfoByName($name){
        $key = 'user_'.$name;
        $user = Redis::get($key);
        if(!$user){
            $user = Db::table('wa_users')->where('username',$name)->get();
            Redis::set($key,$user);
        }
        return $user;
    }
    // 记录用户金币日志
    static function usercoin_record($data){
        $in = Db::table("wa_usercoin_record")->insert($data);
        if($in){
            return 1;
        }else{
            return 0;
        }
    }
     // 获取用户信息
    static function getuserinfobyaccount($account){
        $ifexit = Db::table("wa_users")->where("username",$account)->first();
        $user['id']=$ifexit->id;
        $user['username']=$ifexit->username;
        $user['nickname']=$ifexit->nickname;
        $user['coin']=(string)$ifexit->score;
        $user['money']=(string)$ifexit->money;
        return $user;
    } 

    // 返回json
    static function returndata($action,$data)
    {
        $returndata=[
            'action'=>$action,
            'data'=>$data
        ];
       return json_encode($returndata,JSON_UNESCAPED_SLASHES);
    }
    // redis取数据
    static function getRedis($key){
        return Redis::get($key);
    }
    // 更新redis数据
    static function setRedis($key,$value){
        return Redis::set($key,$value);
    }
    // 删除redis数据
    static function delRedis($key){
        return Redis::del($key);
    }
    // 获取配置文件
    static function getConfig($key){
        return config($key);
    }

     // 用户登录
    static function userlogin($data){
        $ifexit = Db::table("wa_users")->where("username",$data['account'])->first();
        $infonull['id'] = '';
        $infonull['username'] = '';
        $infonull['nickname'] = '';
        $infonull['coin'] = '';
        $infonull['money'] = '';
        $infonull['token'] = '';

        if(!$ifexit){
            $rs['code']=1002;
            $rs['msg']='用户名不存在';
            $rs['info']=$infonull;
            return $rs;
        }
        if($ifexit->isrobot == 1){
            $rs['code']=1085;
            $rs['msg']='机器人账号不允许登录';
            $rs['info']=$infonull;
            return $rs;
        }

        $comparepass = self::comparepass($data['pass'],$ifexit->password);
       
        if(!$comparepass){
            $rs['code']=1003;
            $rs['msg']='密码错误';
            $rs['info']=$infonull;
            return $rs;           
        }
        if($ifexit->status==1){
            $rs['code']=1004;
            $rs['msg']='账号被锁定，暂时无法登录';
            $rs['info']=$infonull;
            return $rs; 
        }
        
        $user['userinfo'] = self::getuserinfobyaccount($data['account']); 
        $user['userinfo']['token'] = self::updatetoken($data['account']);
        
        $rs['code']=1;
        $rs['msg']='登录成功';
        $rs['info']=$user;
        return $rs;
    }

    static function comparepass($pass,$mypass){
        if(md5($pass) != $mypass){
            return false;
        }else{
            return true;
        }
    }

    static function checktoken($client_id,$uid,$token){
        $user = Db::table('wa_users')->where("id",$uid)->value('token');
     //    var_dump($user,$token);
        if(!$user){
             $data=[
                 'code'=>10020,
                 'msg'=>'用户不存在',
                 'info'=>''
             ];
             Gateway::sendToClient($client_id,Common::returndata('usernotexit',$data));
             exit();
             return 10020;
        }
        if($user && $user!= $token){
         $data=[
             'code'=>700,
             'msg'=>'您的登录已过期，请重新登录',
             'info'=>''
         ];
             Gateway::sendToClient($client_id,Common::returndata('tokenexpire',$data));
             exit();
             return 700;
        }
        return 1;
 
     }
 

        /**
         *设置登录token  唯一性
        *@param $phone 用户手机号
        *@retrun  String 
        */
    static function setToken($phone){
        $str = md5(uniqid(md5(microtime(true)),true));
        $token = sha1($str.$phone);
        return $token;
    }

    static function updatetoken($phone){
        // $str = md5(uniqid(md5(microtime(true)),true));
        // $token = sha1($str.$phone);
       $user =  Db::table("wa_users")->where("username",$phone)->first();
        return $user->token;
    }

    // 获取期号
    static function getexpect(){
        $hour = date("H");
		$min =date("i");
		// $hour = 1;
		// $min =15;
		$a = $hour*60+$min;

		if($a<1000 && $a>100){
			$a='0'.$a;
		}
		if($a<100){
			$a='00'.$a;
		}
		return date('Ymd').$a;
    }

    // 操作用户金币   type : 0 减少  ；  1增加
    static function updateusercoin($uid,$coin,$type,$remark='' ){
        // var_dump($uid);die;
        $userinfo = Common::getuserinfo($uid);
        if($type==0){
            $paytype = 0;
            $newcoin = $userinfo['coin']-$coin;
        }else{
            $paytype = 1;
            $newcoin = $userinfo['coin']+$coin;
        }
        
        $up = Db::table("wa_users")->where("id", $uid)->update(['score'=>$newcoin]);

        // 设置请求参数
        $data = [
            'username' => $userinfo['username'],
            'amount'   => $coin,
            'type'     => $type,
        ];
        // 设置头部信息
        $headers = [
            'company-code: 31',
            'Content-Type: application/json',
        ];

        $sign = makesign($data);
        self::curlPost($data, $headers, $sign);

        if($up){
            $data=[
                'uid'=>$uid,
                'coin'=>$coin,
                'type'=>$paytype,
                'remark'=>$remark,
                'addtime'=>date('Y-m-d H:i:s',time()),
            ];
           $record =  Db::table("wa_usercoin_record")->insert($data);
            return 1;
        }else{
            return 0;
        }
    
    }
    // 获取用户金币余额
    static function getusercoin($uid){
        $user = Db::table("wa_users")->where("id",$uid)->first();
        return $user->score;
    }
    static function checktoken2($client_id,$uid,$token){
        $user = Db::table('wa_users')->where("id",$uid)->value('token');
     //    var_dump($user,$token);
        if(!$user){
             $data=[
                 'code'=>10020,
                 'msg'=>'用户不存在',
                 'info'=>''
             ];
             return 10020;
        }
        return 1;
 
     }
     public static function updatetoken2($id){
        // $str = md5(uniqid(md5(microtime(true)),true));
        // $token = sha1($str.$id);
        $user = Db::table("wa_users")->where("id",$id)->first();
        return $user->token;
    }
    public static function getuserinfobyid($id){
        $ifexit = Db::table("wa_users")->where("id",$id)->first();

        $user['id']=$ifexit->id;
        $user['username']=$ifexit->username;
        $user['nickname']=$ifexit->nickname;
        $user['coin']=(string)$ifexit->score;
        $user['money']=$ifexit->money;
        $user['token']=$ifexit->token;
        return $user;
    } 

    // 检查url
    public static function checkurl($client_id,$data){
   
        $datas = explode('&',$data['data']['data']);
        foreach($datas as $k =>$v){
            $chai = explode('=',$v);
            
            $a[0]=$chai[0];
            $a[1]=$chai[1];
            $new[]=$a;
        }
        // var_dump($new);die;
        foreach($new as $kt =>$vt){
            $b[$vt[0]]=$vt[1];
            $new2=$b;  //所有前端给的参数都在这里接受.  传的啥可以直接取出来
        }

        $checktoken =   Common::checktoken2($client_id,$new2['uid'],$new2['token']);
        if($checktoken!=1){
            Gateway::sendToClient($client_id,Common::returndata('tokenexpire',$data));
            exit();
        }
        $user['userinfo']['token'] = self::updatetoken2($new2['uid']);
        $user['userinfo'] = self::getuserinfobyid($new2['uid']); 
        $rs['code']=1;
        $rs['msg']='登录成功';
        $rs['info']=$user;
        return $rs;
    }

    public static function getconfig2()
    {   
        $config = Db::table("wa_options")->where("name","system_config")->select("value")->get();
        $config= json_decode($config,1);
        $config = json_decode($config[0]['value'],1);
        // var_dump($config);die;
        $data['title']=$config['logo']['title'];
        $data['banquan']="山东万有引擎公司";
        $data['logo']=$config['logo']['siteurl'].$config['logo']['image'];
        $data['gamestatus']=$config['logo']['gamestatus'];
        if(!$data['gamestatus']){
            $data['gamestatus']='off';
        }
        $data['logintype']=$config['logo']['logintype'];
        $data['logintype']=$config['logo']['logintype'];
        $data['paystatus']='off';
        if(!$data['paystatus']){
            $data['paystatus']='off';
        }
        $data['duihuanstatus']='off';
        if(!$data['duihuanstatus']){
            $data['duihuanstatus']='off';
        }
        $info['code']=1;
        $info['msg']='success';

        $info['info']=$data;

        return $info;
    }

    public static function userreg($data)
    {       
        if($data['pass']!=$data['pass2']){
            $rs['code']=1001;
            $rs['msg']='两次密码不一致';
            $rs['info']='';
            return $rs;
        }
        $ifexit = Db::table("wa_users")->where("username",$data['account'])->first();
        // var_dump($ifexit);die;
        if($ifexit){
            $rs['code']=1002;
            $rs['msg']='用户名已存在';
            $rs['info']='';
            return $rs;
        }
        $user = [
            'username'=>$data['account'],
            'nickname'=>self::createNickname(),
            'password'=>md5($data['pass']),
            'sex'=>'1',
            'avatar'=>'',
            'email'=>'',
            'mobile'=>'',
            'level'=>0,
            'birthday'=>date("Y/m/d H:i:s",time()),
            'money'=>'0.00',
            'score'=>0,
            'last_time'=>date("Y/m/d H:i:s",time()),
            'last_ip'=>$_SERVER['REMOTE_ADDR'],
            'join_time'=>date("Y/m/d H:i:s",time()),
            'join_ip'=>$_SERVER['REMOTE_ADDR'],
            'token'=>self::setToken($data['account']),
            'created_at'=>date("Y/m/d H:i:s",time()),
            'updated_at'=>date("Y/m/d H:i:s",time()),
            'role'=>1,
            'status'=>0
        ];

        
       $in = Db::table('wa_users')->insert($user);
       if($in){
            $rs['code']=1;
            $rs['msg']='注册成功';
            $rs['info']='';
            return $rs;
       }else{
            $rs['code']=1003;
            $rs['msg']='注册失败';
            $rs['info']='';
            return $rs;
       }
    }

    // 用户登录
    // public static function userlogin($data){
    //     $ifexit = Db::table("wa_users")->where("username",$data['account'])->first();
    //     $infonull['id'] = '';
    //     $infonull['username'] = '';
    //     $infonull['nickname'] = '';
    //     $infonull['coin'] = '';
    //     $infonull['money'] = '';
    //     $infonull['token'] = '';

    //     if(!$ifexit){
    //         $rs['code']=1002;
    //         $rs['msg']='用户名不存在';
    //         $rs['info']=$infonull;
    //         return $rs;
    //     }
    //     if($ifexit->isrobot == 1){
    //         $rs['code']=1085;
    //         $rs['msg']='机器人账号不允许登录';
    //         $rs['info']=$infonull;
    //         return $rs;
    //     }

    //     $comparepass = self::comparepass($data['pass'],$ifexit->password);
    
    //     if(!$comparepass){
    //         $rs['code']=1003;
    //         $rs['msg']='密码错误';
    //         $rs['info']=$infonull;
    //         return $rs;           
    //     }
    //     if($ifexit->status==1){
    //         $rs['code']=1004;
    //         $rs['msg']='账号被锁定，暂时无法登录';
    //         $rs['info']=$infonull;
    //         return $rs; 
    //     }
        
    //     $user['userinfo'] = self::getuserinfo($data['account']); 
    //     $user['userinfo']['token'] = self::updatetoken($data['account']);
    //     $rs['code']=1;
    //     $rs['msg']='登录成功';
    //     $rs['info']=$user;
    //     return $rs;
    // }

    static function getlucky_expect(){
        $startTime = strtotime(date("Y-m-d", time())); //当天开始时间时间戳
        $nowtime = time()-$startTime;
        $qihao = floor($nowtime/60/12)+1;
        if($qihao<100){
            $qihao ='0'.$qihao;
        }
        $expect = date('Ymd').$qihao;
        return $expect;
    }



    /**
     *  curlPost
     *
     * @return mixed
     */
    static function curlPost($data, $headers, $sign)
    {
        $data['sign'] = $sign;
        // 初始化 CURL
        $ch = curl_init('http://111.173.89.245:9090/index.php/api/config/changeBalances');
        // 设置 CURL 配置
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        // 执行 CURL 请求
        $response = curl_exec($ch);
        // 检查是否有错误发生
        if ($response === false) {
            echo 'Curl error: ' . curl_error($ch);
        }
        // 关闭 CURL
        curl_close($ch);
        // 获取响应内容
        return json_decode($response, true);
    }


}